function MainAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
}

MainAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the scene is first created */

	this.autoTest = false;
	this.timer = null;
	this.timeout = 0;
	this.skiptime = 100;
	this.isStopUpdate = false;
	this.wanStatusUpdated = false;
	this.wanservice = "unknow";
	this.autoTestCondition = 15;
	this.isAutoTestRunning = false;

	//Instantiate the auto test toggle button
	this.controller.setupWidget('ToggleB_autotest', 
		{
			modelProperty: "value",
			trueLabel: 'A',
			falseLabel: 'M'
		},
		this.toggleModel = {
			value: this.autoTest,
			disabled: false,
		}
	);
	this.controller.listen("ToggleB_autotest", Mojo.Event.propertyChange, this.switchTestMode.bind(this));

	//Instantiate the CTWAP APN switch button
	this.controller.setupWidget("Button_ctwap",
	        {
	        },
	        {
	            label : "CTWAP",
				buttonClass: 'secondary',
	            disabled: false
	        });
	this.controller.listen("Button_ctwap",Mojo.Event.tap, this.switchToCTWAP.bind(this));
	
	//Instantiate the CTNET APN switch button
	this.controller.setupWidget("Button_ctnet",
	        {
	        },
	        {
	            label : "CTNET",
				buttonClass: 'secondary',
	            disabled: false
	        });
	this.controller.listen("Button_ctnet",Mojo.Event.tap, this.switchToCTNET.bind(this));

	//Create a collapser to show APN switch result.
	this.resultOfAPNSwitch = new Collapser(this, 'Collapser_result', 'APN SWITCH RESULT');

	//Create a collapser to show test contents.
	this.testDisplay = new Collapser(this, 'Collapser_test', 'URL TEST');

	//Configure test url label.
	this.testURL = this.controller.get('Label_testurl');
	this.controller.listen("Label_testurl", Mojo.Event.tap, this.submitURL.bind(this));
	//Load test url label into test contents collapser.
	this.testDisplay.insert(this.testURL);

	//Configure test result label.
	this.testRet = this.controller.get('Label_testresult');
	this.testDisplay.insert(this.testRet);

    //Initialize auto test area
	this.controller.setupWidget("IPicker_condition",
		{
			label: 'second',
			labelPlacement: Mojo.Widget.labelPlacementRight,
			modelProperty: 'value',
			min: 0,
			max: 30
		},
		{
			value: this.autoTestCondition
		}
	);
	this.controller.listen(
		"IPicker_condition", 
		Mojo.Event.propertyChange,
		function(event){
			this.autoTestCondition = event.value;
		}.bind(this)); 

	this.controller.setupWidget("Button_autotestctrl",
		{
		},
		this.autoTestButtonModel = {
			label : "Start",
			buttonClass: 'secondary',
			disabled: false
		});
	this.controller.listen("Button_autotestctrl", Mojo.Event.tap, this.handleAutoTest.bind(this));
	
	//this.switchTestMode({value: this.autoTest});
	
	/* use Mojo.View.render to render view templates and add them to the scene, if needed */
	
	/* setup widgets here */
	
	/* add event handlers to listen to events from widgets */
};

MainAssistant.prototype.prepareSwitch = function(){
	this.clear();
	
	if (this.timer != null) {
		Mojo.Log.info("prepareSwitch: clear timer");
		clearInterval(this.timer);
	}
	this.timeout = 0;	
	this.timer = setInterval(this.timerUpdate.bind(this), this.skiptime);
	
	this.disableToggleButtion(true);
};

MainAssistant.prototype.switchTestMode = function(event){
	Mojo.Log.error("switchTestMode: event.value=" + event.value);
	this.clear();
	if (event.value) {
		this.autoTest = true;
		$(Title).innerHTML = "Auto Test";
		$('layout_auto').show();
		$('layout_manual').hide();
		$('layout_testurl').hide();
	} else {
		this.autoTest = false;
		$(Title).innerHTML = "Manual Test";
		this.controller.get('layout_auto').hide();
		this.controller.get('layout_manual').show();
		$('layout_testurl').show();		
		this.updateWANStatus();
	}
};

MainAssistant.prototype.switchToCTWAP = function() {
	this.prepareSwitch();
	this.displayWanStatus("ctwap_switch_start");
	this.controller.serviceRequest('palm://com.palm.wan/', {
		method: 'connectservice',
		parameters: {
			'service': 'mms',
			'usage': 'userInitiated'
		},
		onSuccess: function(rsp) {			
			this.displayWanStatus('ctwap_connecting_ok');
			
			Mojo.Log.info("++++++Success to activate CTWAP");
			Mojo.Log.info(Object.toJSON(rsp));
			Mojo.Log.info("------Success to activate CTWAP");
		}.bind(this),
		
		onFailure: function(rsp) {
			this.displayWanStatus('ctwap_connecting_failed');
			
			Mojo.Log.info("++++++Failed to activate CTWAP");
			Mojo.Log.info(Object.toJSON(rsp));
			Mojo.Log.info("------Failed to activate CTWAP");
		}.bind(this)
	});
	
	this.updateWANStatus();
};

MainAssistant.prototype.switchToCTNET = function() {
	this.prepareSwitch();
	this.displayWanStatus("ctnet_switch_start");
	this.controller.serviceRequest('palm://com.palm.wan/', {
		method: 'disconnectservice',
		parameters: {
			'service': 'mms'
		},
		onSuccess: function(rsp) {			
			this.displayWanStatus('ctnet_connecting_ok');
			
			Mojo.Log.info("++++++Success to activate CTNET");
			Mojo.Log.info(Object.toJSON(rsp));
			Mojo.Log.info("------Success to activate CTNET");
		}.bind(this),
		
		onFailure: function(rsp) {
			this.displayWanStatus('ctnet_connecting_failed');
			
			Mojo.Log.info("++++++Failed to activate CTNET");
			Mojo.Log.info(Object.toJSON(rsp));
			Mojo.Log.info("------Failed to activate CTNET");
		}.bind(this)
	});
	
	this.updateWANStatus();
};

MainAssistant.prototype.updateWANStatus = function() {
    this.controller.serviceRequest('palm://com.palm.wan', {
         method: 'getstatus',
         parameters: {subscribe:true},
		 
         onSuccess: function(rsp){
			if (this.isStopUpdate) {
				return;
			}
			if (!rsp.hasOwnProperty('connectedservices')) {
				return;
			}
			
		 	var isFindService = false;
			var serviceInfo = rsp["connectedservices"];
			
			for (var i = 0; i < serviceInfo.length; i++) {
				for (var j = 0; j < serviceInfo[i].service.length; j++) {
					if (serviceInfo[i].service[j] == "mms" ||
						serviceInfo[i].service[j] == "internet") {
						isFindService = true;
						this.wanservice = serviceInfo[i].service[j];
						break;
					}
				}
								
				if (isFindService) {							
					if ( serviceInfo[i].connectstatus == "dormant" ||
						 serviceInfo[i].connectstatus == "active" ) {
						if (this.timer != null) {
							clearInterval(this.timer);
							this.timer = null;
						}

						Mojo.Log.info("this.timeout=" + this.timeout + 'ms');
						
						if (this.autoTestCondition <= this.timeout) {
							this.handleAutoTest();
						}
						
						switch (this.wanservice) {
							case "mms":
								this.displayWanStatus('ctwap_connected');
							break;
							
							case "internet":
								this.displayWanStatus('ctnet_connected');
							break;
						}
						
						if (this.autoTest && this.isAutoTestRunning) {
							setTimeout(
								function(){
									if (this.wanservice == 'mms') {
										this.switchToCTNET();
									} else {
										this.switchToCTWAP();
									}
								}.bind(this),
								1000);
						} else if (!this.autoTest){
							this.disableToggleButtion(false);
							this.tryTestURL();
						} else {
							this.disableToggleButton(false);
						}
						
						this.isStopUpdate = true;
					}
					break;
				}
			}			
			Mojo.Log.info(Object.toJSON(rsp));

		}.bind(this),
		
		onFailure: function(rsp){
			Mojo.Log.info("updateWANStatus --- onFailure");
			
			if (this.isStopUpdate) {
				return;
			}
			
			if (this.timer != null) {
				clearInterval(this.timer);
				this.timer = null;			
			}
			
			this.displayWanStatus('get_status_failed');
		
			this.isStopUpdate = true;
			this.disableToggleButtion(false);
			
		}.bind(this)

     });
	 this.isStopUpdate = false;
};

MainAssistant.prototype.displayWanStatus = function(status){
	var appendHTML = function(s) {
		this.resultOfAPNSwitch.appendHTML( s + " - [" + this.timeout + "]<br>");
	}.bind(this);
	
	switch (status) {
		case "ctwap_switch_start":
			appendHTML("Start switching to CTWAP");
		break
		
		case "ctnet_switch_start":
			appendHTML("Start switching to CTNET");
		break;
		case 'ctwap_connecting_ok':
			appendHTML("Success to activate CTWAP");
		break;
		
		case "ctwap_connecting_failed":
			appendHTML("Failed to activate CTWAP");
		break;
		
		case 'ctwap_connected':
			appendHTML("CTWAP is ready now");
		break;

		case 'ctnet_connecting_ok':
			appendHTML("Success to activate CTNET");
		break;
		
		case "ctnet_connecting_failed":
			appendHTML("Failed to activate CTNET");
		break;
		
		case 'ctnet_connected':
			appendHTML("CTNET is ready now");
		break;
		
		case 'get_status_failed':
			appendHTML("Failed to get wan status");
		break;
		
		default:
		break;
	}
};

MainAssistant.prototype.timerUpdate = function(){
	this.timeout += this.skiptime;
};

MainAssistant.prototype.clear = function(){
	this.resultOfAPNSwitch.setHTML("");
	this.testURL.innerHTML = "";
	this.testRet.innerHTML = "";
	this.timeout = 0;
	this.isStopUpdate = false;
};

MainAssistant.prototype.tryTestURL = function(){
	switch (this.wanservice) {
		case "mms":
			this.testURL.innerHTML = "http://10.234.63.197/";
		break;
		case "internet":
			//this.testURL.innerHTML = "http://www.china-goldcard.com/";
			this.testURL.innerHTML = 'http://wap.118114.cn/bst/strip12/txt.jsp?colid=5000&colcd=1086&fr=bst&pd=300';
		break;
	}
	
	//If auto test, don't try test URL, just test the APN switch.
	//if (!this.autoTest) this.submitURL();
};

MainAssistant.prototype.submitURL = function(){
	new Ajax.Request(this.testURL.innerHTML, { 
		method: 'get',
		onSuccess: function(rsp) {
			this.testRet.innerHTML = rsp.responseText;
		}.bind(this),
		
		onFailure: function(rsp) {
			this.testRet.innerHTML = Object.toJSON(rsp);
		}.bind(this)
	}); 
	
	this.testRet.innerHTML = "Loading...";
};

MainAssistant.prototype.handleAutoTest = function(){
	
	if (this.autoTestButtonModel.label == 'Start') {
		//Start the auto test
		this.autoTestButtonModel.label = 'Stop';
		this.controller.modelChanged(this.autoTestButtonModel);
		this.isAutoTestRunning = true;
		//this.disableToggleButtion(true);
		
		this.clear();
		this.updateWANStatus();	
		
	} else if (this.autoTestButtonModel.label == 'Stop') {
		//Stop the auto test
		this.autoTestButtonModel.label = 'Start'
		this.controller.modelChanged(this.autoTestButtonModel);
		this.isAutoTestRunning = false;
		//this.disableToggleButtion(false);
	}
};

MainAssistant.prototype.disableToggleButtion = function(disalbe){
	if (this.toggleModel.disabled != disalbe) {
		this.toggleModel.disabled = disalbe;
		this.controller.modelChanged(this.toggleModel);
	}
}

MainAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
};

MainAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
};

MainAssistant.prototype.cleanup = function(event) {
	/* this function should do any cleanup needed before the scene is destroyed as 
	   a result of being popped off the scene stack */
};
